$(function() {

    // change to register
    var $loginBox = $('#loginBox')
    var $registerBox = $('#registerBox')
    var $userInfo = $('#userInfo')

    $loginBox.find("a").on('click', function() {
        $registerBox.show()
        $loginBox.hide()
    })

    

    // change to login
    $registerBox.find('a').on('click', function() {
        $loginBox.show()
        $registerBox.hide()
    })

    // register
    $registerBox.find("button").on("click", () => {
        var username = $registerBox.find('[name="username"]').val()
        var password = $registerBox.find('[name="password"]').val();
        var repassword = $registerBox.find('[name="repassword"]').val()

        console.log(username, password, repassword)
        $.ajax({
          type: "post",
          url: '/api/user/register',
          data: {
              username: username,
              password: password,
              repassword: repassword
          },
          dataType: "json",
          success: function(result) {

            $registerBox.find('#colWarning').html(result.message)
            
            console.log("registerd:", result)
            if (!result.code) {
                //这册成功
                setTimeout(function() {
                   $loginBox.show()
                   $registerBox.hide()
                }, 1000)
            } else { 
                
            }
          }
        })
    })


    // login
    $loginBox.find('button')
    .on('click', function() {
        console.log('clicked login')
        $.ajax({
            type: 'post',
            url: '/api/user/login',
            data: {
                username: $loginBox.find('[name="username"]').val(),
                password: $loginBox.find('[name="password"]').val()
            },
            dataType: 'json',
            success: function(result) {

                console.log('login result',result)
                
                $loginBox.find('.colWarning').html(result.message)
                
                if (!result.code) {
                    window.location.reload()
                    return
                    // setTimeout(() => {
                    //     $loginBox.hide()
                    //     $userInfo.show()
                    //     $userInfo.find('.username').html(result.user.username)
                    //     $userInfo.find('.info').html('你好，欢迎光临我的博客')
                    // }, 1000)
                }
            }
        })
    })

    // lougout
    $("#logout").on("click", function(){
       $.ajax({
            url: '/api/user/logout',
            success: function(result) {
                console.log(XPathResult)
                if (!result.code) {
                    window.location.reload()
                }
            }
       })
    })
})

